package com.kordar.admin.kernel.util;

import com.kordar.rbac.AuthManager;
import com.kordar.rbac.Permission;
import com.kordar.rbac.Role;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HelperUtil {

    public static final char UNDERLINE = '_';

    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 8      * 下划线转驼峰
     * 9
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = Pattern.compile("_(\\w)").matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    public static String humpToWord(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append(' ');
                sb.append(c);
            } else {
                if (i == 0) {
                    c = Character.toUpperCase(c);
                }
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static String humpToLine(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append(UNDERLINE);
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static String timeStamp2Date(long seconds, String format) {
        if (seconds == 0) {
            return "";
        }
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(seconds * 1000));
    }

    public static List<Map<String, Object>> layuiPermissionTree(Set<Permission> permissions) {
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        for (Permission entry : permissions) {
            String[] dirs = entry.getName().substring(1).split("/");
            Permission p = entry;
            String key = dirs[0];
            if (dirs.length >= 3) {
                key = dirs[0] + "/" + dirs[1];
            }
            List<Map<String, Object>> children;
            if (map.containsKey(key)) {
                children = map.get(key);
            } else {
                children = new ArrayList<>();
            }
            Map<String, Object> n = new HashMap<>();
            n.put("id", p.getName());
            n.put("desc", p.getDescription());
            children.add(n);
            map.put(key, children);
        }

        List<Map<String, Object>> list = new ArrayList<>();
        for (Map.Entry<String, List<Map<String, Object>>> entry : map.entrySet()) {
            Map<String, Object> item = new HashMap<>();
            item.put("title", entry.getKey());
            item.put("checked", false);
            item.put("spread", false);
            List<Map<String, Object>> children = new ArrayList<>();

            entry.getValue().forEach(m -> {
                Map<String, Object> itemChild = new HashMap<>();
                itemChild.put("title", m.get("id") + " [" + m.get("desc") + "]");
                itemChild.put("id", m.get("id"));
                itemChild.put("field", "name");
                itemChild.put("checked", false);
                itemChild.put("spread", true);
                children.add(itemChild);
            });

            if (!children.isEmpty()) {
                item.put("children", children);
            }

            list.add(item);
        }

        return list;
    }

    public static List<Map<String, Object>> layuiRoleTree(Set<Role> role, String disabled) {
        List<Map<String, Object>> tree = new ArrayList<>();
        role.forEach(e -> {
            Map<String, Object> m = new HashMap<>();
            m.put("title", e.getName());
            m.put("field", "name");
            m.put("id", e.getName());
            m.put("checked", false);
            m.put("spread", false);
            m.put("disabled", e.getName().equals(disabled));
            tree.add(m);
        });
        return tree;
    }

    public static void scanPermission(String filter, AuthManager authManager) {
        RequestMappingHandlerMapping mapping = SpringUtil.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            RequestMappingInfo info = m.getKey();
            HandlerMethod method = m.getValue();

            String classname = method.getMethod().getDeclaringClass().getName();
            if (classname.startsWith(filter)) {
                PatternsRequestCondition p = info.getPatternsCondition();
                for (String url : p.getPatterns()) {

                    if ("/".equals(url)) {
                        continue;
                    }

                    Permission permission = authManager.createPermission(url);



                    if (url.contains("add")) {
                        permission.setDescription("添加");
                    }

                    else if (url.contains("save")) {
                        permission.setDescription("保存");
                    }

                    else if (url.contains("form")) {
                        permission.setDescription("表单");
                    }

                    else if (url.contains("batch-delete")) {
                        permission.setDescription("批量删除");
                    }

                    else if (url.contains("delete")) {
                        permission.setDescription("删除");
                    }

                    else if (url.contains("list")) {
                        permission.setDescription("列表");
                    }

                    else if (url.contains("index")) {
                        permission.setDescription("首页");
                    }

                    else if (url.contains("edit")) {
                        permission.setDescription("修改");
                    }

                    else {
                        permission.setDescription("节点");
                    }

                    try {
                        authManager.add(permission);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
